package org.web.abc.stockanalysis.server.biz.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.web.abc.stockanalysis.server.domain.StockBasicDO;
import org.web.abc.stockanalysis.server.domain.StockTaskDO;
import org.web.abc.stockanalysis.server.domain.query.QueryStockBasic;
import org.web.abc.stockanalysis.server.domain.query.QueryStockTask;
import org.web.abc.stockanalysis.server.service.StockBasicService;
import org.web.abc.stockanalysis.server.service.StockTaskService;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ServiceExceptionHelper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("mainTaskBizImpl")
public class MainTaskBizImpl {

    // 1. 创建阻塞队列，指定容量为10
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(10);

    @Resource
    private StockBasicService stockBasicService;

    @Resource
    private StockTaskService stockTaskService;

    public String doTask(BatchTaskDO batchTaskDO) {
        try {
            QueryStockBasic queryStockBasic = buildQueryStockBasicByBatchTaskDO(batchTaskDO);
            List<StockBasicDO> selectedStockBasicList = stockBasicService.selectStockBasicList(queryStockBasic);

            if (batchTaskDO.getExecuteDate() == null) {
                throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.PARAM_EMPTY, "ExecuteDate is null");
            }

            QueryStockTask queryStockTask = new QueryStockTask();
            queryStockTask.setAnalysisTaskName(batchTaskDO.getTaskDefinitionEnum().getTaskName());
            queryStockTask.setExecuteDate(batchTaskDO.getExecuteDate());
            queryStockTask.setAllRecords();
            List<StockTaskDO> stockTaskDOList = stockTaskService.selectStockTaskList(queryStockTask);
            Map<String, StockTaskDO> stockTaskDOMapByStockCode = stockTaskDOList.stream()
                    .collect(Collectors.toMap(StockTaskDO::getStockCode, Function.identity()));

            // 创建线程池（可根据 CPU 核心数调整）
            int threadCount = 3;
            ExecutorService executor = Executors.newFixedThreadPool(threadCount);
            // 用 CountDownLatch 来等待所有任务执行完成
            CountDownLatch latch = new CountDownLatch(selectedStockBasicList.size());

            List<StockBasicDO> filterSelectedStockBasicList = new ArrayList<>();
            for (StockBasicDO stockBasicDO : selectedStockBasicList) {
                StockTaskDO stockTaskDOFromDB = stockTaskDOMapByStockCode.get(stockBasicDO.getStockCode());
                if (stockTaskDOFromDB != null && stockTaskDOFromDB.getAnalysisStatus().equals("completed")) {
                    latch.countDown();
                    continue;
                }
                filterSelectedStockBasicList.add(stockBasicDO);
            }

            for (StockBasicDO stockBasicDO : filterSelectedStockBasicList) {
                StockTaskDO stockTaskDOFromDB = stockTaskDOMapByStockCode.get(stockBasicDO.getStockCode());
                if (stockTaskDOFromDB != null && stockTaskDOFromDB.getAnalysisStatus().equals("completed")) {
                    latch.countDown();
                    continue;
                }
                StockTaskDO stockTaskDO = new StockTaskDO();
                stockTaskDO.setStockCode(stockBasicDO.getStockCode());
                stockTaskDO.setStockName(stockBasicDO.getStockName());
                stockTaskDO.setAnalysisTaskName(batchTaskDO.getTaskDefinitionEnum().getTaskName());
                stockTaskDO.setExecuteDate(batchTaskDO.getExecuteDate());
                stockTaskDO.setStockBasicDO(stockBasicDO);
                StockDayTradeTask stockDayTradeTask = new StockDayTradeTask(stockTaskService, latch, stockTaskDO, batchTaskDO);
                executor.submit(stockDayTradeTask);
            }
            latch.await();
            System.out.println("所有任务执行完成！");
            executor.shutdown();
            return "所有任务执行完成";
        } catch (Exception e) {
            return ServiceExceptionHelper.getExceptionInfo(e);
        }
    }

    private QueryStockBasic buildQueryStockBasicByBatchTaskDO(BatchTaskDO batchTaskDO) {
        QueryStockBasic queryStockBasic = new QueryStockBasic();
        if (StringUtils.isNotEmpty(batchTaskDO.getStockCode())) {
            queryStockBasic.setStockCode(batchTaskDO.getStockCode());
        }
        queryStockBasic.setIsStockSt(Byte.valueOf("0"));
        queryStockBasic.setAllRecords();
//            queryStockBasic.setPageNum(1);
//            queryStockBasic.setPageSize(100);
        return queryStockBasic;

    }

}
